#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：turbo 
@File    ：views.py
@Author  ：赵加响
@Date    ：2023/4/23 10:37 
@Desc    ：
"""
from django.http import FileResponse
from rest_framework.views import APIView

from apps.common.serializers import RoleDropdownSerializer, MenuDropdownSerializer
from apps.lookups.calendars.models import Calendar
from apps.rbac.models import Role, Menu
from bases.response import SuccessResponse
from bases.viewsets import APIReadOnlyViewSet


class RoleDropdownViewSet(APIReadOnlyViewSet):
    queryset = Role.objects.all().order_by('id')
    serializer_class = RoleDropdownSerializer
    # 由于角色本身数据较少，因此dropdown不需要分页
    pagination_class = None


class MenuDropdownViewSet(APIReadOnlyViewSet):
    queryset = Menu.objects.all().order_by('id')
    serializer_class = MenuDropdownSerializer
    pagination_class = None


class FileResponseApi(APIView):

    def get(self, request, path, path_level, filename, download_name):
        """
        获取文件流，在此之前需要手动校验文件是否存在
        @param request:
        @param path: 文件路径
        @param path_level: 静态文件目录层数
        @param filename: 文件名，需要有文件名后缀
        @param download_name: 下载文件名，不需要文件名后缀
        @return:
        """
        filepath = path.joinpath('/'.join(filename[:path_level]))
        extension = filename.split('.')[-1]
        response = FileResponse(open(filepath.joinpath(filename), 'rb'), filename=f'{download_name}.' + extension)
        return response


class CalendarApi(APIView):

    def get(self, request):
        calendar = request.GET.get('calendar_type')

        calendars = Calendar.objects.filter(calendar_type__calendar_type__exact=calendar)

        calendar_list = []
        for calendar in calendars:
            data = dict()
            data['date'] = calendar.calendar_date.strftime('%Y-%m-%d')
            data['holiday'] = calendar.date_type
            calendar_list.append(data)

        return SuccessResponse(calendar_list)
